package nsqio

import (
	"encoding/json"
	"errors"
	"gitee.com/liukexing/mqbroker/core/driver/logger"
	"gitee.com/liukexing/mqbroker/core/typedef"
)

type NsqRequestHandle struct {
	parent *NsqPubSub
}

func (m *NsqRequestHandle) Praise(v []byte) (interface{}, bool) {
	req := typedef.RequestData{}
	if logger.CheckErr(typedef.ErrInfo{
		Info: Config.Info,
		Err:  json.Unmarshal(v, &req),
	}) {
		return nil, true
	}
	return req, false
}

func (m *NsqRequestHandle) Process(data interface{}) error {
	req := data.(typedef.RequestData)
	if v, ok := m.parent.ReplyFunc.Load(req.Topic); ok {
		handle := v.(typedef.ReplyHandle)
		reqdata, ok := handle.Praise(req.Data)
		if ok {
			return m.Response(typedef.ReplyData{
				Topic: req.Topic,
				ReqID: req.ReqID,
				Error: true,
				Data:  "Data Praise Error",
			})
		}
		rsp, err := handle.Process(reqdata)
		if err != nil {
			return m.Response(typedef.ReplyData{
				Topic: req.Topic,
				ReqID: req.ReqID,
				Error: true,
				Data:  err.Error(),
			})
		}
		return m.Response(typedef.ReplyData{
			Topic: req.Topic,
			ReqID: req.ReqID,
			Error: false,
			Data:  rsp,
		})
	}
	return nil
}

func (m *NsqRequestHandle) Response(data typedef.ReplyData) error {
	jsv, err := json.Marshal(data)
	if logger.CheckErr(typedef.ErrInfo{
		Info: Config.Info,
		Err:  err,
	}) {
		return err
	}
	if m.parent.Publish("Response", string(jsv)) {
		return errors.New("Publish Message Failed")
	}
	return nil
}
